package concurrent.threadPool;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPoolExecutorTest {

    public static void main(String[] args) throws InterruptedException {

        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                1, 2,
                5, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(2),
                new CallerRunsPolicy());
        executor.prestartAllCoreThreads(); //初始化核心线程

        Runnable runnable = new Runnable() {

            private AtomicInteger count = new AtomicInteger(1);

            @Override
            public void run() {
                while (true) {
                    executor.execute(new MyTask(count));
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        Thread thread = new Thread(runnable);
        thread.start();
        thread.join();
    }

}

class MyTask implements Runnable {

    private int index;

    public MyTask(AtomicInteger count) {
        this.index = count.getAndIncrement();
    }

    @Override
    public void run() {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("任务结束：" + index);
    }
}
